<template>
  <div id="reg_ret_box"  v-show="show_button">
    <div class="form-container"> 
      <!-- 选择表单类型 -->
      <div class="form-selector">
        <button
          v-for="(title, index) in sections"
          :key="index"
          :class="['selector-btn', { active: selectedForm === title }]"
          @click="switchForm(title)"
        >
          {{ title }}
        </button>
        <button class="selector-btn" @click="closeForm">关闭</button>
      </div>

      <!-- 动态渲染表单 -->
      <div v-for="(item, index) in fields" :key="index">
        <!-- 不需要分步的表单 -->
        <div v-if="selectedForm === item.title && !item.step">
          <h2>{{ item.title }}</h2>
          <div v-for="field in item.fields" :key="field.id" class="form-group">
            <label :for="field.id">{{ field.label }}</label>
            <input
              :type="field.type"
              :id="field.id"
              :autocomplete="field.autocomplete"
              v-model="formData[field.id]"
              :placeholder="field.placeholder"
            />
          </div>
          <button class="submit-btn" @click="handleSubmit(item.func)">
            提交{{ item.title }}
          </button>
        </div>
        <!-- 需要分步的表单 -->
        <div v-if="(selectedForm===item.title) && item.step">
          <h2>{{ item.title }}</h2>
          <div
            v-for="(step_, stepIndex) in item.steps"
            :key="stepIndex"
          >
            <div v-if="currentStep == step_.step" class="step">
              <div v-for="field in step_.fields" :key="field.id" class="form-group">
                <label :for="field.id">{{ field.label }}</label>
                <input
                  :type="field.type"
                  :id="field.id"
                  :autocomplete="field.autocomplete"
                  v-model="formData[field.id]"
                  :placeholder="field.placeholder"
                />
              </div>
              <button  v-if="currentStep!==item.step_model.All_Steps"  class="submit-btn" @click="goToNextStep($event, step_.func, item.step_model)">
                下一步
              </button>
              <button  v-if="currentStep===item.step_model.All_Steps"  class="submit-btn" @click="goToNextStep($event, step_.func, item.step_model)">
                提交
              </button>

              <button
                v-if="currentStep > 1"
                class="back-btn"
                @click="goToPreviousStep()"
              >
                上一步
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, defineProps, watch, onMounted ,defineEmits} from 'vue';
// 需要注意section和title需要一致。
// 整个emit是必须的用来控制组件的显示。
const props = defineProps({
  show_button: {
    type: Boolean,
    required: true,
    default:true,
  },
  myimg: {
    type: String,
    required: false,
  },
  sections: {
    type: Array,
    required: true,
    default: () => ['注册', '找回密码'],
  },
  fields: {
    type: Array,
    required: true,
    default: () => [
      {
        title: '注册',
        fields: [
          { id: 'username', label: '用户名', type: 'text', placeholder: '请输入用户名', autocomplete: 'off' },
          { id: 'password', label: '密码', type: 'password', placeholder: '请输入密码', autocomplete: 'off' },
          { id: 'confirmPassword', label: '确认密码', type: 'password', placeholder: '请再次输入密码', autocomplete: 'off' },
          { id: 'email', label: '邮箱', type: 'email', placeholder: '请输入邮箱', autocomplete: 'off' },
        ],
        step: false, // 不需要分步
        func: () => { 
          console.log('提交注册!');
        }
      },
      {
        title: '找回密码',
        step: true, // 需要分步
        steps: [
          {
            step: 1,
            fields: [
              { id: 'username', label: '账户', type: 'text', placeholder: '请输入要找回的账号', autocomplete: 'off' },
              { id: 'email', label: '邮箱', type: 'email', placeholder: '请输入注册邮箱', autocomplete: 'off' },
            ],
            func: () => {
              console.log('第一步附带函数!');
              return true
              
            }
          },
          {
            step: 2,
            fields: [
              { id: 'verificationCode', label: '验证码', type: 'text', placeholder: '请输入验证码', autocomplete: 'off' },
            ],
            func: () => {
              console.log('第二步附带函数!');
            }
          },
          {
            step: 3,
            fields: [
              { id: 'newPassword', label: '新密码', type: 'password', placeholder: '请输入新密码', autocomplete: 'off' },
              { id: 'confirmNewPassword', label: '确认新密码', type: 'password', placeholder: '请再次输入新密码', autocomplete: 'off' },
            ],
            func: () => {
              console.log('第三步附带函数!');
            }
          },
        ],
        step_model: {
          current: 1,
          All_Steps: 3,
        },
      },
    ]
  },
});

const emit = defineEmits(['close_formdata'])

// 当前选择的表单类型
const selectedForm = ref(props.sections[0]);

// 当前步骤（用于分步表单）
const currentStep = ref(1);

// 表单数据
const formData = reactive({});

const closeForm = function () { 
  emit("close_formdata",false)
}
// 初始化表单数据
const initializeFormData = () => {
  props.fields.forEach((item) => {
    if (item.fields) {
      item.fields.forEach((field) => {
        formData[field.id] = '';
      });
    }
    if (item.steps) {
      item.steps.forEach((step) => {
        step.fields.forEach((field) => {
          formData[field.id] = '';
        });
      });
    }
  });
};

// 切换表单类型
const switchForm = (formType) => {
  selectedForm.value = formType;
  currentStep.value = 1;
  initializeFormData();
};

// 处理表单提交
const handleSubmit = (func) => {
  if (func) {
    func(formData);
  }
};

// 下一步
const goToNextStep = async (event, func, stepModel) => {
  if (func) {
    if (await func(formData)) {
      if (currentStep.value <stepModel.All_Steps) {
        currentStep.value++;
      }
    } else {
      return  
    }
  }
   

};

// 上一步
const goToPreviousStep = () => {
  if (currentStep.value > 1) {
    currentStep.value--;
  }
};

// 初始化表单数据
initializeFormData();
onMounted(() => {
  // 由于使用占位报错
  if (props.myimg) { 
    const img= 'url('+String(props.myimg)+')'
    document.documentElement.style.setProperty('--bg-image', img );
  }
});
</script>

<style scoped>
--root{
  --bg-image:""
}


#reg_ret_box {
  background-image: var(--bg-image);
  background-repeat: no-repeat;
  background-size: cover;
  width: 100vw;
  height: 100vh;
  background-position: center;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.form-container {
  max-width: 400px;
  width: 100%;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  background-color: white;
  margin-top: -200px; /* 你可以根据需要调整这个值 */
}

.form-selector {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.selector-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  background-color: #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.selector-btn.active {
  background-color: #6a11cb;
  color: white;
}

.selector-btn:hover {
  background-color: #ddd;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.form-group {
  margin-bottom: 15px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #555;
}

input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
}

.submit-btn,
.back-btn {
  width: 100%;
  padding: 10px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
  margin-top: 3px;
}

.submit-btn {
  background-color: #6a11cb;
  color: white;
  margin-bottom: 10px;
}

.submit-btn:hover {
  background-color: #2575fc;
}

.back-btn {
  background-color: #f0f0f0;
  color: #333;
}

.back-btn:hover {
  background-color: #ddd;
}
</style>